package com.Policing.Polling;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import androidx.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.JavaBean.OffSaveSiteDate;
import com.Policing.LogUtils;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.Policing.x5Tb.FileDisplayActivity;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sakura.bottommenulibrary.bottompopfragmentmenu.BottomMenuFragment;
import sakura.bottommenulibrary.bottompopfragmentmenu.MenuItem;

public class Site_Data extends BaseActivity implements OnDismissListener, AMapLocationListener {
    private TextView pointName, number, job, labor, tool, title_text;
    private ImageView fh, rfid_set;
    private List<Content_Bean> data = new ArrayList<>();
    private List<String> IDS = new ArrayList<>();
    private String id = "", taskId = "";
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private ListView site_list;
    private String taskPointId = "",startDate="",endDate="";
    private Content_Adapter content_adapter;
    private String url = "http://" + Ip_Set.IP + "/api/taskPointContentQuery";
    private String locationUpload = "http://" + Ip_Set.IP + "/api/locationUpload";
    private String urlup = "http://" + Ip_Set.IP + "/api/pointSubmit";
    private String task = "http://" + Ip_Set.IP + "/api/taskPointContentAction";
    private String look_url = "http://" + Ip_Set.IP + "/api/pointContentFileQuery";//附件
    private List<String> listTaskPointContentId;//保存要提交的路点内容检查的ID
    @Override
    public int intiLayout() {
        return R.layout.site_data;
    }

    @Override
    public void initView() {
        listTaskPointContentId = new ArrayList<>();
        getLocation();
        rfid_set = (ImageView) findViewById(R.id.rfid_set);
        rfid_set.setImageResource(R.mipmap.chakan);
        rfid_set.setOnClickListener(v -> {
            Intent intent = new Intent(Site_Data.this, Step_Imag.class);
            intent.putExtra("pointId", id);
            startActivity(intent);
        });
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("路点信息");
        pointName = (TextView) findViewById(R.id.pointName);
        number = (TextView) findViewById(R.id.number);
        job = (TextView) findViewById(R.id.job);
        labor = (TextView) findViewById(R.id.labor);
        tool = (TextView) findViewById(R.id.tool);
        site_list = (ListView) findViewById(R.id.site_list);
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
        site_list.setOnItemClickListener((parent, view, i, id) -> {

            if (data.get(i).getResult().equals("异常")) {
                return;
            }

            new BottomMenuFragment(Site_Data.this)
                    .addMenuItems(new MenuItem("正常"))
                    .addMenuItems(new MenuItem("异常"))
                    .addMenuItems(new MenuItem("查看附件"))
                    .setOnItemClickListener((menu_item, position) -> {
                        if (position == 0) {
                            updata(data.get(i).getPointContentId(), i, "1");
                        }
                        if (position == 1) {
                            Intent intent = new Intent(Site_Data.this, Polling_Scheme.class);
                            intent.putExtra("taskPointContentId", data.get(i).getPointContentId());
                            intent.putExtra("pointContentId", IDS.get(i));
                            intent.putExtra("id", String.valueOf(i));
                            startActivityForResult(intent, 8);
                        }
                        if (position == 2) {
                            Look_file(IDS.get(i));
                        }
                    })
                    .show();

        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void initData() {
        taskPointId = getIntent().getExtras().getString("taskPointId");
        taskId = getIntent().getExtras().getString("taskId");
        load();
        Calendar calendar=Calendar.getInstance();
android.icu.text.SimpleDateFormat sdf = new android.icu.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        startDate=sdf.format(calendar.getTime());
    }

    private void Look_file(final String id) {
        if (Since_case.set().getONorOff()) {
            Log.i("llllllllll", "222");
            Map<String, String> map = new HashMap<>();
            map.put("pointContentId", id);
            map.put("source", Since_case.set().getSource());
            HttpOkHttp.getInstance().requestPost(look_url, map, new HttpOkHttp.OkHttpCallBack<String>() {
                @Override
                public void requestSuccess(String s) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        String link = jsonObject.getString("link").replace("139.9.120.216", Ip_Set.IP);
                        Log.e("数据", link);
                        Log.e("数据", s);
                        if (jsonObject.getString("state").equals("1")) {
                            Intent intent = new Intent(Site_Data.this, FileDisplayActivity.class);
                            //记得排查并把它加回来,原本是jsonObject.getString("link");
                            intent.putExtra("url", link);
                            if (!jsonObject.getString("file").equals("")) {
                                String str1 = jsonObject.getString("file").substring(0, jsonObject.getString("file").indexOf("."));
                                String str2 = jsonObject.getString("file").substring(str1.length() + 1, jsonObject.getString("file").length());
                                intent.putExtra("file", str2);
                                intent.putExtra("id", id);
                                startActivity(intent);
                            } else {
                                showToast("没有附件！");
                                Log.e("数据", "没有附件");
                            }
                            // showToast("暂不可用");
                        }
                        if (jsonObject.getString("state").equals("0")) {
                            showToast("没有附件！");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void requestFailure(String message) {
                    Log.i("llllllllll", message);
                }
            }, String.class);
        }else {
            showToast("离线巡检暂不支持附件查看");
        }
    }

    public void submit(View view) {
        Log.d("进来没有", "submit: 进来没有？" );
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getResult().equals("未检")) {
                toastShort("请全部检查后提交！！");
                return;
            }

        }
        if (Since_case.set().getONorOff()) {
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Site_Data.this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        Map<String, String> map = new HashMap<>();
                        map.put("taskPointId", taskPointId);
                        map.put("source", Since_case.set().getSource());
                        HttpOkHttp.getInstance().requestPost(urlup, map, new HttpOkHttp.OkHttpCallBack<String>() {
                            @Override
                            public void requestSuccess(final String s) {
                                Log.d("进来没有", "submit: 进来没有？接口里面");
                                Gson gson = new Gson();
                                java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                                }.getType();
                                final Site_Data_bean jsonBean = gson.fromJson(s, type);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (jsonBean.getState().equals("1")) {
                                            finish();
                                            toastShort("上传成功！！");
                                        }
                                    }
                                });
                            }

                            @Override
                            public void requestFailure(String message) {
                                Log.i("datadata", message);
                            }
                        }, String.class);
                    }
                    if (position == -1) {
                    }
                }
            }).setCancelable(true).setOnDismissListener(Site_Data.this).show();
        } else {
            new AlertView(" 提示！", "是否保存数据", "取消", new String[]{"确定"}, null, Site_Data.this, AlertView.Style.Alert, new OnItemClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onItemClick(Object o, int position) {
                    Calendar calendar=Calendar.getInstance();
                    android.icu.text.SimpleDateFormat sdf = new android.icu.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    endDate=sdf.format(calendar.getTime());
                    if (Since_case.set().getOffSaveSiteDate() != null) {
                        Since_case.set().getOffSaveSiteDate().add(new OffSaveSiteDate(listTaskPointContentId, taskPointId,startDate,endDate));
                        int i = Since_case.set().getRouteStatusPosition().indexOf(taskPointId);
                        Since_case.set().getSiteActivityBeans().get(Since_case.set().getLxPosition()).getTaskPoints().get(i).setStatus("3");
                        Log.e("测试数据", Since_case.set().getLxPosition() + "--" + routeCode);
                        finish();
                        toastShort("保存成功");
                    } else {
                        List<OffSaveSiteDate> list = new ArrayList<>();
                        list.add(new OffSaveSiteDate(listTaskPointContentId, taskPointId,startDate,endDate));
                        Since_case.set().setOffSaveSiteDate(list);
                        int i = Since_case.set().getRouteStatusPosition().indexOf(taskPointId);
                        Since_case.set().getSiteActivityBeans().get(Since_case.set().getLxPosition()).getTaskPoints().get(i).setStatus("3");
                        Log.e("测试数据新建", String.valueOf(listTaskPointContentId.size()) + "位置" + i);
                        finish();
                        toastShort("保存成功");
                    }

                }
            }).setCancelable(true).setOnDismissListener(Site_Data.this).show();
        }

    }

    private Site_Data_bean beans;

    private void load() {
        if (Since_case.set().getONorOff()) {
            Map<String, String> map = new HashMap<>();
            map.put("taskPointId", taskPointId);
            map.put("source", Since_case.set().getSource());
            map.put("isOffline", "1");
            HttpOkHttp.getInstance().requestPost(url, map, new HttpOkHttp.OkHttpCallBack<String>() {
                @Override
                public void requestSuccess(final String s) {
                    LogUtils.d(s);
                    Gson gson = new Gson();
                    java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                    }.getType();
                    final Site_Data_bean jsonBean = gson.fromJson(s, type);

                    runOnUiThread(() -> {
                        data.clear();
                        IDS.clear();
                        if (jsonBean.getState().equals("1")) {
                            Bitmap bitmap = null;
                            pointName.setText(jsonBean.getPoint().getPointName());
                            number.setText(jsonBean.getPoint().getNumber());
                            job.setText(jsonBean.getPoint().getJob());
                            labor.setText(jsonBean.getPoint().getLabor());
                            tool.setText(jsonBean.getPoint().getTool());
                            for (int i = 0; i < jsonBean.getPointContents().size(); i++) {
                                String result = "";
                                if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("0")) {
                                    result = "异常";
                                    InputStream is = getResources().openRawResource(R.mipmap.yi);
                                    bitmap = BitmapFactory.decodeStream(is);
                                    Log.i("123123", String.valueOf(i));
                                }
                                if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("1")) {
                                    result = "正常";
                                    InputStream is = getResources().openRawResource(R.mipmap.gou);
                                    bitmap = BitmapFactory.decodeStream(is);
                                    Log.i("1231234", String.valueOf(i));
                                }
                                if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("2")) {
                                    Log.i("1231235", String.valueOf(i));
                                    bitmap = null;
                                    result = "未检";
                                }
                                data.add(new Content_Bean(jsonBean.getPointContents().get(i).getPointContent().getProject(), jsonBean.getPointContents().get(i).getPointContent().getMethods(),
                                        jsonBean.getPointContents().get(i).getPointContent().getFrequency(), result,
                                        jsonBean.getPointContents().get(i).getTaskPointContentId(), jsonBean.getPointContents().get(i).getPointContent().getStandard(),
                                        jsonBean.getPointContents().get(i).getPointContent().getMatters(), bitmap
                                ));
                                IDS.add(jsonBean.getPointContents().get(i).getPointContent().getPointContentId());
                                id = jsonBean.getPointContents().get(i).getPointContent().getPointId();
                            }
                            content_adapter = new Content_Adapter(Site_Data.this, R.layout.content_item, data);
                            site_list.setAdapter(content_adapter);
                            for (int i = 0; i < data.size(); i++) {
                                if (data.get(i).getResult().equals("未检")) {
                                    site_list.setSelection(i);
                                    break;
                                }
                            }
                        }

                    });


                    Log.i("datadata", s);
                }

                @Override
                public void requestFailure(String message) {
                    Log.i("datadata", message);
                }
            }, String.class);
        } else {
            routeCode = Since_case.set().getListPointTaskId().indexOf(taskPointId);
            if (routeCode != -1) {
                final Site_Data_bean jsonBean = Since_case.set().getSiteDataBeans().get(routeCode);
                beans = jsonBean;
                //Log.e("数据", jsonBean.getPointContents().get(0).getPointContent().getFrequency());
                runOnUiThread(() -> {
                    data.clear();
                    IDS.clear();
                    if (jsonBean.getState().equals("1")) {
                        Bitmap bitmap = null;
                        pointName.setText(jsonBean.getPoint().getPointName());
                        number.setText(jsonBean.getPoint().getNumber());
                        job.setText(jsonBean.getPoint().getJob());
                        labor.setText(jsonBean.getPoint().getLabor());
                        tool.setText(jsonBean.getPoint().getTool());
                        for (int i = 0; i < jsonBean.getPointContents().size(); i++) {
                            String result = "";
                            if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("0")) {
                                result = "异常";
                                InputStream is = getResources().openRawResource(R.mipmap.yi);
                                bitmap = BitmapFactory.decodeStream(is);
                                Log.i("123123", String.valueOf(i));
                            }
                            if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("1")) {
                                result = "正常";
                                InputStream is = getResources().openRawResource(R.mipmap.gou);
                                bitmap = BitmapFactory.decodeStream(is);
                                Log.i("1231234", String.valueOf(i));
                            }
                            if (jsonBean.getPointContents().get(i).getPointContent().getResult().equals("2")) {
                                Log.i("1231235", String.valueOf(i));
                                bitmap = null;
                                result = "未检";

                            }
                            data.add(new Content_Bean(jsonBean.getPointContents().get(i).getPointContent().getProject(), jsonBean.getPointContents().get(i).getPointContent().getMethods(),
                                    jsonBean.getPointContents().get(i).getPointContent().getFrequency(), result,
                                    jsonBean.getPointContents().get(i).getTaskPointContentId(), jsonBean.getPointContents().get(i).getPointContent().getStandard(),
                                    jsonBean.getPointContents().get(i).getPointContent().getMatters(), bitmap
                            ));
                            IDS.add(jsonBean.getPointContents().get(i).getPointContent().getPointContentId());
                            id = jsonBean.getPointContents().get(i).getPointContent().getPointId();

                        }
                        content_adapter = new Content_Adapter(Site_Data.this, R.layout.content_item, data);
                        site_list.setAdapter(content_adapter);
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getResult().equals("未检")) {
                                site_list.setSelection(i);
                                break;
                            }
                        }
                    }

                });
            }
        }
    }

    private int routeCode;
    private void locationload(String location) {
        Map<String, String> map = new HashMap<>();
        map.put("location", location);
        map.put("taskId", taskId);
        map.put("source",Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(locationUpload, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(final String s) {
                Log.i("123123", s);
            }

            @Override
            public void requestFailure(String message) {
                Log.i("datadata", message);
            }
        }, String.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent string) {
        super.onActivityResult(requestCode, resultCode, string);
        Log.e("数据", resultCode + "-" + requestCode);
        if (Since_case.set().getONorOff()){
            //应该不需要什么东西
        }else {
            if (resultCode == 8) {
                String id = string.getStringExtra("id");
                updata(data.get(Integer.parseInt(id)).getPointContentId(), Integer.parseInt(id), "0");
            } else {
                String id = string.getStringExtra("id");
                updata(data.get(Integer.parseInt(id)).getPointContentId(), Integer.parseInt(id), "1");
            }
        }
      /*  if (requestCode==1&&resultCode==3){
            String id = string.getExtras().getString("id");
            updata(data.get(Integer.parseInt(id)).getPointContentId(),Integer.parseInt(id),"1");
        }*/
    }

    @Override
    public void onDismiss(Object o) {

    }


    @Override
    protected void onDestroy() {
        try {
            mlocationClient.onDestroy();
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        new AlertView(" 提示！", "是否退出！！！", "取消", new String[]{"确定"}, null, Site_Data.this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                //取消：position=-1,确定 position=0
                if (position == 0) {
                    finish();
                }
                if (position == -1) {
                    return;
                }
            }
        }).setCancelable(true).setOnDismissListener(Site_Data.this).show();

    }

    private void updata(String taskPointContentId, int position1, String result) {//路点正常或异常
        if (Since_case.set().getONorOff()) {
            Map<String, String> map = new HashMap<>();
            map.put("taskPointContentId", taskPointContentId);
            map.put("source", Since_case.set().getSource());
            HttpOkHttp.getInstance().requestPost(task, map, new HttpOkHttp.OkHttpCallBack<String>() {
                @Override
                public void requestSuccess(final String s) {
                    Gson gson = new Gson();
                    java.lang.reflect.Type type = new TypeToken<Site_Data_bean>() {
                    }.getType();
                    final Site_Data_bean jsonBean = gson.fromJson(s, type);
                    runOnUiThread(() -> {
                        if (jsonBean.getState().equals("1")) {
                            load();
                        }
                    });
                    Log.i("datadata", s);
                }

                @Override
                public void requestFailure(String message) {
                    Log.i("datadata", message);
                }
            }, String.class);
        } else {
            if (result.equals("1")) {
                listTaskPointContentId.add(taskPointContentId);
                Since_case.set().getSiteDataBeans().get(routeCode).getPointContents().get(position1).getPointContent().setResult("1");
                load();
            }
            if (result.equals("0")) {
                //提交异常不需要提交路点
                try {
                    int i = listTaskPointContentId.indexOf(taskPointContentId);
                    if (i != -1) {
                        listTaskPointContentId.remove(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //listTaskPointContentId.add(taskPointContentId);
                Since_case.set().getSiteDataBeans().get(routeCode).getPointContents().get(position1).getPointContent().setResult("0");
                load();
            }
        }
    }

    private static void nnn() {
        System.out.println("你真的是无敌了哈，66666");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (Since_case.set().getONorOff()) {
            load();
        }
    }

    private void getLocation() {
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(60000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                Log.e("定位数据", amapLocation.getLongitude() + "," + amapLocation.getLatitude());
                locationload(amapLocation.getLongitude() + "," + amapLocation.getLatitude());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }else {
            LogUtils.e("测试数据为空");
        }
    }

    //Toast提示工具方法
    private void showToast(final String data) {
        runOnUiThread(() -> Toast.makeText(Site_Data.this, data, Toast.LENGTH_SHORT).show());
    }
}
